

// panel/index.js, this filename needs to match the one registered in package.json
Editor.Panel.extend({
  // css style for panel
  style: `
    :host {
    }

    .container {
      display: flex;
      flex-flow: column wrap;
      align-items: center;
      justify-content: center;
    }
    
    .row {
      width: 100%;
      align-self: flex-start;
      display: inline-flex;
    }

    .ctex {
      font-weight: 900;
      color: #fd942b;
    }
    .btn {
      border: 1px solid black;
      border-radius: 3px;
    }
    .btn:active {
      box-shadow: inset 0px 3px 5px black;
    }
    .btn:focus { 
      border-color: #fd942b;
    }
    .btn-red {
      background: #b54344;
      color: #bdbdbd;
    }
    .btn-amber {
      background: #cc9631;
      color: #262626;
    }
    .btn-normal {
      background: #4e4e4e;
      color: #bdbdbd;
    }
  `,

  // html template for panel
  template: `
    <!-- <div>State: <span id="label">--</span></div> -->
    <style type="text/css">.inner {padding:0}input,input:focus{color:#fd942b}:host{display:inline-block;position:relative;box-sizing:border-box;width:auto;margin:0 .25em 0 0;outline:0;cursor:default;overflow:hidden;border-radius:3px;border:1px solid #171717}:host(:last-child){margin-right:0}input{font-family:Roboto,-apple-system,BlinkMacSystemFont,'Helvetica Neue',Arial,'Segoe UI',Oxygen,Ubuntu,Cantarell,'Open Sans',SourceHanSansCN-Normal,sans-serif;border:none;margin:0;padding:.16666667em .5em;width:100%;display:inline-block;outline:0;background:#262626}input::-webkit-input-placeholder{font-style:italic;color:#595959}input::selection{color:#fff;background:#09f}:host(:hover){}:host([focused]){border-color:#fd942b}:host([unnavigable]){border:none;border-bottom:1px solid rgba(255,255,255,.23)}:host([is-disabled]){pointer-events:none}:host([is-disabled]) input{color:#636363;background:#3a3a3a}:host(.mini) input{font-size:.66666667rem;height:initial}:host(.tiny) input{font-size:.83333333rem;height:initial}:host(.small) input{font-size:.91666667rem;height:initial}:host input{font-size:1rem;height:19px}:host(.large) input{font-size:1.16666667rem;height:initial}:host(.big) input{font-size:1.33333333rem;height:initial}:host(.huge) input{font-size:1.5rem;height:initial}:host(.massive) input{font-size:1.83333333rem;height:initial}
//# sourceURL=theme://elements/input.css</style>
    <div id="main" class="container" >
      <!--<div style="position:absolute;right:0;top:0;">
      </div> -->
      <div class="row" id="coms">
      </div>
      <div class="row">
        <input id="com_name" style="height:2em;" placeholder="输入要添加的组件名" type="">
        <button class="btn btn-normal" style="width:50px" id="btn">
          <span style="width: 50px;">
            <i class="icon-plus"></i>
          </span>
        </button>
      </div>
      <div id="list" style="border:1px dashed gray; width:100%">
      </div>
    </div>
    <div id="tip">请选择节点</div>
    <div style="position:absolute; right:0;bottom:0;">
      <button class="btn btn-amber" style="color:#262626;display:none;" id="btn_del_copy_data">🗑</button>
      <button class="btn btn-amber" style="color:#262626;display:none;" id="btn_paste">粘贴属性</button>
      <button class="btn btn-amber" style="color:#262626;display:none;" id="btn_paste_com">粘贴组件</button>
      <button class="btn btn-amber" id="btn_help">?</button>
    </div>
  `,

  // element and variable binding
  $: {
    btn: '#btn',
    btnHelp: '#btn_help',
    btnPaste: '#btn_paste',
    btnDelCopyData: '#btn_del_copy_data',
    btnPasteCom: '#btn_paste_com',
    eb: "#com_name",
    list: "#list",
    main: "#main",
    tip: "#tip",
    curComs: "#coms",
  },

  curMatchs: [],
  // method executed when template and styles are successfully loaded and initialized
  ready() {
    this.$main.onkeydown = (e) => {
      // console.log("keydown", e.keyCode);
    };
    this.$eb.oninput = this.onInput2.bind(this);
    this.$eb.onkeydown = (e) => {
      if (e.keyCode == 13) {
        if (this.curMatchs.length > 0) {
          this.addCom(this.curMatchs[0].origin);
        }
      }
    };
    this.$btn.onclick = () => {
      if (this.curMatchs.length > 0) {
        this.addCom(this.curMatchs[0].origin);
      }
    };

    this.$btnDelCopyData.onclick = () => {
      Editor.Scene.callSceneScript('add_component', 'del-copy-data', null, (err) => {
        if (err) {
          return;
        }
      });
    };
    this.$btnPaste.onclick = () => {
      Editor.Scene.callSceneScript('add_component', 'paste-component-property', null, (err) => {
        if (err) {
          return;
        }
      });
    };
    this.$btnPasteCom.onclick = () => {
      Editor.Scene.callSceneScript('add_component', 'paste-component', null, (err) => {
        if (err) {
          return;
        }
      });
    };
    this.$btnHelp.onclick = () => {
      Editor.Dialog.messageBox(null, {
        message:
          `💆‍♀️主人您好！我是您的开发女仆小可，希望我能帮到您，让您的COCOS开发变得得心应手！❤

💡 您可以在输入框中输入组件名字，我会寻找并列出匹配的组件。按回车或点"+"按钮添加组件（列表中的第一个）或点击列表中的按钮添加组件。对了，可以多选节点，这样会对所有节点添加组件噢。

💡 红色列表是当前节点的组件，如果有多个组件存在，会有数字表示。点击红色按钮可以对组件操作。

🚫 您可以跟我聊天（才怪呢，哼）
          `
      });
    };
    // this.$btnHelp.addEventListener('confirm', () => {

    // });
    // 3️⃣4️⃣5️⃣6️⃣7️⃣8️⃣9️⃣ 发

    this.refresh();
    Editor.log(`小可：初始化完毕，等待主人的任务♥`);

  },

  onInput2() {
    this.curMatchs = [];
    let comName = this.$eb.value;

    let handle = {
      comName: comName,
      res: null
    };

    Editor.Scene.callSceneScript('add_component', 'input-query', handle, (err) => {
      if (err) {
        return;
      }
    });
  },

  addCom(comName) {
    Editor.Scene.callSceneScript('add_component', 'add-component', comName, (err) => {
      if (err) {
        return;
      }
    });
  },

  refresh() {
    if (Editor.Selection.curSelection("node").length > 0) {
      this.$main.style.display = "";
      this.$tip.style.display = "none";

      this.$curComs.style.display = "";
      this.refreshCurComs();
    }
    else {
      this.$main.style.display = "none";
      this.$tip.style.display = "";

      this.$curComs.style.display = "none";
      this.$curComs.innerHTML = "";
    }
  },
  refreshCurComs() {
    Editor.Scene.callSceneScript('add_component', 'list-current-components', {}, (err) => {
      if (err) {
        console.log("list-current-components, err:", err);
        return;
      }
    });
  },
  componentMenu(comOpt) {
    let electron = require("electron");
    var template = [
      // { label: '取消' },
      // {
      //   label: '复制组件属性', click: () => {
      //     Editor.Scene.callSceneScript('add_component', 'copy-component-property', comOpt, (err) => {
      //       if (err) {
      //         console.log("复制组件属性错误:", err);
      //         return;
      //       }
      //     });
      //   }
      // },
      {
        label: '复制', click: () => {
          Editor.Scene.callSceneScript('add_component', 'copy-component', comOpt, (err) => {
            if (err) {
              console.log("复制错误:", err);
              return;
            }
          });
        }
      },
      {
        label: '删除', click: () => {
          Editor.Scene.callSceneScript('add_component', 'del-component', comOpt, (err) => {
            if (err) {
              console.log("删除组件错误:", err);
              return;
            }
          });
        }
      },
      // { ... }
    ];
    let menu = electron.remote.Menu.buildFromTemplate(template);
    menu.popup();
  },

  // register your ipc messages here
  messages: {
    "add_component:dock"(event, type) {
      console.log("panel:dock");
    },
    "selection:selected"(event, type) {
      if (type == "node") {
        this.refresh();
      }
    },
    "selection:unselected"(event, type) {
      if (type == "node") {
        this.refresh();
      }
    },
    "add_component:res-input-query"(event, matchs) {
      console.log("query-res", matchs);
      this.$list.innerHTML = "";
      if (matchs.length > 20) {
        matchs = matchs.slice(0, 20);
      }
      console.log("match:", matchs);
      matchs.forEach(match => {
        let ctex = match.input; //spr
        let index = match.index; //3

        let html = "";
        for (let i = 0; i < match.origin.length; i++) {
          //文字变色加粗
          if (i == index) {
            html += `<span class="ctex">${match.origin.substring(i, index + ctex.length)}</span>`;
            i += ctex.length;
          }
          if (i < match.origin.length) {
            html += match.origin[i];
          }
          // console.log("html:", html, "ctex", ctex);
        }

        let handle = document.createElement("button");
        handle.className = "btn btn-normal";
        handle.innerHTML = html;
        handle.onclick = () => {
          this.addCom(match.origin);
        }
        this.$list.appendChild(handle);
      });
      this.curMatchs = matchs.slice();
    },
    "add_component:res-list-current-components"(event, comOptionCol) {
      this.$curComs.innerHTML = "";
      //生成UI
      for (let key in comOptionCol) {
        let co = comOptionCol[key];
        // console.log(co.comName, co);
        let handle = document.createElement("button");
        handle.className = "btn btn-red";
        handle.setAttribute("name", co.comName);
        handle.style.background = "#b54344";
        handle.innerHTML = `${co.nodeUuids.length > 1 ? `<span class="ctex">${co.nodeUuids.length}</span>|` : ""}${co.comName}`;
        handle.onclick = () => {
          this.componentMenu(co);
        };
        this.$curComs.appendChild(handle);
      }
    },
    "add_component:res-add-component"(event, comOpt) {
      Editor.log(`小可: 主人的任务已经全部完成♥`);
      this.refresh();
    },
    "add_component:res-del-component"(event, comName) {
      // console.log(this.$curComs);
      let handles = this.$curComs.querySelectorAll("button");
      for (let i = 0; i < handles.length; i++) {
        let handle = handles[i];
        if (handle.getAttribute("name") == comName) {
          handle.remove();
          break;
        }
      }
      Editor.log(`小可: 主人的任务已经全部完成♥`);
    },
    "add_component:res-copy-component"(event, copyData) {
      let cd = null;
      try {
        cd = JSON.parse(copyData);
      }
      catch (e) {
        console.warn("parseCopyDataErr:", e);
      }
      if (cd.err) {
        Editor.log(`小可: 复制组件失败：${cd.err}💔`);
        return;
      }
      console.log(cd);
      let handles = this.$curComs.querySelectorAll("button");
      for (let i = 0; i < handles.length; i++) {
        let handle = handles[i];
        if (handle.getAttribute("name") == cd.comName) {
          Editor.log(`小可: 已复制组件。♥`);
          this.$btnPasteCom.innerText = "粘贴:" + cd.comName;
          this.$btnPasteCom.style.display = "";
          this.$btnPaste.innerText = "粘贴:" + cd.comName + "属性";
          this.$btnPaste.style.display = "";
          this.$btnDelCopyData.style.display = "";
          return;
          break;
        }
      }
      Editor.log(`小可: 小可没找到组件，复制失败。💔`);
    },
    
    "add_component:res-del-copy-data"(event, type) {
      this.$btnPasteCom.style.display = "none";
      this.$btnPaste.style.display = "none";
      this.$btnDelCopyData.style.display = "none";
    },
  }
});